{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 日期时间创建和转换\n",
    "\n",
    "本教程介绍Pandas中创建和转换日期时间数据的各种方法，包括to_datetime()、date_range()等核心函数。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "from datetime import datetime, date"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 学习目标\n",
    "\n",
    "通过本教程，你将学会：\n",
    "\n",
    "1. **使用`pd.to_datetime()`转换各种格式的日期字符串**\n",
    "   - 自动识别常见日期格式\n",
    "   - 指定格式提高转换性能\n",
    "   - 处理无效日期数据\n",
    "\n",
    "2. **使用`pd.date_range()`创建日期序列**\n",
    "   - 指定开始/结束日期和周期数\n",
    "   - 使用不同的频率代码\n",
    "   - 创建工作日序列\n",
    "\n",
    "3. **掌握其他日期创建方法**\n",
    "   - 周期范围（Period）\n",
    "   - 时间差范围（Timedelta）\n",
    "   - 从DataFrame组件创建日期\n",
    "\n",
    "4. **应用到实际场景**\n",
    "   - 股票交易日生成\n",
    "   - 财务报表日期创建\n",
    "\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. pd.to_datetime() - 字符串转日期时间\n",
    "\n",
    "这是最常用的日期时间转换函数。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.1 基本用法\n",
    "\n",
    "`pd.to_datetime()` 是Pandas中最常用的日期时间转换函数，它可以：\n",
    "\n",
    "- **将字符串转换为Timestamp对象**：单个字符串会返回`pd.Timestamp`对象\n",
    "- **将列表/数组转换为DatetimeIndex**：多个日期会返回`DatetimeIndex`\n",
    "- **自动识别多种日期格式**：ISO 8601、美式、欧式等常见格式\n",
    "\n",
    "**关键参数**：\n",
    "- `format`：指定日期格式字符串（可选，但能提高性能）\n",
    "- `errors`：错误处理方式（'raise'、'coerce'、'ignore'）\n",
    "- `dayfirst`：是否将日期解析为\"日/月/年\"格式（默认False）\n",
    "- `yearfirst`：是否将日期解析为\"年/月/日\"格式（默认False）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "字符串: 2023-06-15\n",
      "转换后: 2023-06-15 00:00:00\n",
      "类型: <class 'pandas._libs.tslibs.timestamps.Timestamp'>\n",
      "\n",
      "日期列表转换:\n",
      "DatetimeIndex(['2023-01-01', '2023-02-15', '2023-03-30'], dtype='datetime64[ns]', freq=None)\n"
     ]
    }
   ],
   "source": [
    "# 基本用法\n",
    "date_str = '2023-06-15'\n",
    "dt = pd.to_datetime(date_str)\n",
    "print(f\"字符串: {date_str}\")\n",
    "print(f\"转换后: {dt}\")\n",
    "print(f\"类型: {type(dt)}\")\n",
    "\n",
    "# 转换列表\n",
    "date_list = ['2023-01-01', '2023-02-15', '2023-03-30']\n",
    "dt_series = pd.to_datetime(date_list)\n",
    "print(f\"\\n日期列表转换:\")\n",
    "print(dt_series)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.2 自动格式识别\n",
    "\n",
    "Pandas的`to_datetime()`函数非常智能，可以自动识别多种常见的日期格式：\n",
    "\n",
    "- **ISO 8601标准格式**：`2023-06-15`、`2023-06-15T14:30:00`\n",
    "- **美式格式**：`06/15/2023`、`June 15, 2023`\n",
    "- **欧式格式**：`15/06/2023`、`15-Jun-2023`\n",
    "- **中文格式**：`2023年6月15日`\n",
    "- **带时间的格式**：`2023-06-15 14:30:00`\n",
    "\n",
    "**注意**：虽然自动识别很方便，但在处理大量数据时，明确指定格式可以显著提高性能。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "自动格式识别:\n",
      "2023-06-15           -> 2023-06-15 00:00:00\n",
      "06/15/2023           -> 2023-06-15 00:00:00\n",
      "15-Jun-2023          -> 2023-06-15 00:00:00\n",
      "2023年6月15日           -> 转换失败\n",
      "2023-06-15 14:30:00  -> 2023-06-15 14:30:00\n"
     ]
    }
   ],
   "source": [
    "# 不同格式的自动识别\n",
    "various_formats = [\n",
    "    '2023-06-15',\n",
    "    '06/15/2023',\n",
    "    '15-Jun-2023',\n",
    "    '2023年6月15日',\n",
    "    '2023-06-15 14:30:00'\n",
    "]\n",
    "\n",
    "print(\"自动格式识别:\")\n",
    "for fmt in various_formats:\n",
    "    try:\n",
    "        result = pd.to_datetime(fmt)\n",
    "        print(f\"{fmt:20} -> {result}\")\n",
    "    except:\n",
    "        print(f\"{fmt:20} -> 转换失败\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.3 性能优化：指定格式\n",
    "\n",
    "当处理大量日期数据时，**明确指定日期格式**可以大幅提升性能：\n",
    "\n",
    "**格式化代码说明**：\n",
    "- `%Y`：四位年份（2023）\n",
    "- `%m`：月份（01-12）\n",
    "- `%d`：日期（01-31）\n",
    "- `%H`：小时（00-23）\n",
    "- `%M`：分钟（00-59）\n",
    "- `%S`：秒（00-59）\n",
    "\n",
    "**性能对比**：\n",
    "- 自动推断：需要尝试多种格式，速度较慢\n",
    "- 指定格式：直接按格式解析，速度快2-10倍\n",
    "\n",
    "**最佳实践**：在处理成千上万条日期数据时，始终使用`format`参数。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "281 μs ± 4.05 μs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)\n",
      "195 μs ± 932 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)\n"
     ]
    }
   ],
   "source": [
    "# 指定格式提高性能\n",
    "dates = ['2023-01-01', '2023-02-01', '2023-03-01'] * 1000\n",
    "\n",
    "# 自动推断格式（较慢）\n",
    "%timeit pd.to_datetime(dates[:100])\n",
    "\n",
    "# 指定格式（较快）\n",
    "%timeit pd.to_datetime(dates[:100], format='%Y-%m-%d')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.4 错误处理策略\n",
    "\n",
    "在实际数据处理中，经常会遇到无效的日期数据。`errors`参数提供了三种处理策略：\n",
    "\n",
    "#### **errors='raise'（默认）**\n",
    "- 遇到无效日期时抛出异常\n",
    "- 适用于数据质量要求高的场景\n",
    "- 可以及时发现数据问题\n",
    "\n",
    "#### **errors='coerce'（推荐）**\n",
    "- 将无效日期转换为`NaT`（Not a Time）\n",
    "- 类似于数值中的`NaN`\n",
    "- 便于后续使用`dropna()`或`fillna()`处理\n",
    "- **最常用的选项**\n",
    "\n",
    "#### **errors='ignore'**\n",
    "- 保持原始值不变\n",
    "- 返回原始输入（可能是混合类型）\n",
    "- 适用于需要保留原始数据的场景\n",
    "\n",
    "**实际应用建议**：\n",
    "- 数据清洗阶段：使用`errors='coerce'`，然后检查`NaT`的数量\n",
    "- 生产环境：使用`errors='raise'`，确保数据质量\n",
    "- 探索性分析：使用`errors='ignore'`，先了解数据情况"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "errors='coerce':\n",
      "DatetimeIndex(['2023-01-01', 'NaT', '2023-03-15', 'NaT'], dtype='datetime64[ns]', freq=None)\n",
      "\n",
      "errors='ignore':\n",
      "Index(['2023-01-01', '2023-02-30', '2023-03-15', 'invalid'], dtype='object')\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/var/folders/9b/jb3nnnqn60x3dtlll6mcf0000000gp/T/ipykernel_47080/567584573.py:10: FutureWarning: errors='ignore' is deprecated and will raise in a future version. Use to_datetime without passing `errors` and catch exceptions explicitly instead\n",
      "  result_ignore = pd.to_datetime(mixed_data, errors='ignore')\n"
     ]
    }
   ],
   "source": [
    "# 处理错误数据\n",
    "mixed_data = ['2023-01-01', '2023-02-30', '2023-03-15', 'invalid']\n",
    "\n",
    "# errors='coerce' - 无效值转为NaT\n",
    "result_coerce = pd.to_datetime(mixed_data, errors='coerce')\n",
    "print(\"errors='coerce':\")\n",
    "print(result_coerce)\n",
    "\n",
    "# errors='ignore' - 保持原始值\n",
    "result_ignore = pd.to_datetime(mixed_data, errors='ignore')\n",
    "print(\"\\nerrors='ignore':\")\n",
    "print(result_ignore)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "## 2. pd.date_range() - 创建日期范围\n",
    "\n",
    "`pd.date_range()`是创建规则日期序列的强大工具，常用于：\n",
    "\n",
    "- **时间序列分析**：创建时间索引\n",
    "- **数据对齐**：生成标准时间轴\n",
    "- **模拟数据**：生成测试用的日期序列\n",
    "- **报表生成**：创建报告期间的日期列表\n",
    "\n",
    "### 核心参数组合\n",
    "\n",
    "必须指定以下参数的**至少两个**：\n",
    "1. `start`：起始日期\n",
    "2. `end`：结束日期\n",
    "3. `periods`：生成的日期数量\n",
    "\n",
    "**常用组合**：\n",
    "- `start + end`：生成两个日期之间的所有日期\n",
    "- `start + periods`：从起始日期生成指定数量的日期\n",
    "- `end + periods`：向前推算生成指定数量的日期\n",
    "\n",
    "**其他重要参数**：\n",
    "- `freq`：频率字符串（默认'D'表示天）\n",
    "- `tz`：时区信息\n",
    "- `normalize`：是否将时间标准化为午夜\n",
    "- `name`：返回对象的名称"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. pd.date_range() - 创建日期范围"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.1 频率代码详解\n",
    "\n",
    "频率代码（freq）是`date_range()`的核心参数，决定了日期序列的间隔：\n",
    "\n",
    "#### **日历频率**\n",
    "- `D`：日历日（Calendar day）\n",
    "- `W`：周（默认周日结束）\n",
    "- `M`：月末（Month end）\n",
    "- `MS`：月初（Month start）\n",
    "- `Q`：季度末（Quarter end）\n",
    "- `QS`：季度初（Quarter start）\n",
    "- `Y`：年末（Year end）\n",
    "- `YS`：年初（Year start）\n",
    "\n",
    "#### **时间频率**\n",
    "- `H`：小时（Hour）\n",
    "- `T`或`min`：分钟（Minute）\n",
    "- `S`：秒（Second）\n",
    "- `L`或`ms`：毫秒（Millisecond）\n",
    "- `U`或`us`：微秒（Microsecond）\n",
    "- `N`：纳秒（Nanosecond）\n",
    "\n",
    "#### **工作日频率**\n",
    "- `B`：工作日（Business day，周一至周五）\n",
    "- `BM`：工作日月末\n",
    "- `BMS`：工作日月初\n",
    "- `BQ`：工作日季度末\n",
    "- `BY`：工作日年末\n",
    "\n",
    "**提示**：可以在频率代码前加数字表示倍数，如`2D`表示每2天，`3H`表示每3小时。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "基本日期范围:\n",
      "DatetimeIndex(['2023-01-01', '2023-01-02', '2023-01-03', '2023-01-04',\n",
      "               '2023-01-05', '2023-01-06', '2023-01-07', '2023-01-08',\n",
      "               '2023-01-09', '2023-01-10'],\n",
      "              dtype='datetime64[ns]', freq='D')\n",
      "\n",
      "指定周期数:\n",
      "DatetimeIndex(['2023-01-01', '2023-01-02', '2023-01-03', '2023-01-04',\n",
      "               '2023-01-05', '2023-01-06', '2023-01-07', '2023-01-08',\n",
      "               '2023-01-09', '2023-01-10'],\n",
      "              dtype='datetime64[ns]', freq='D')\n",
      "\n",
      "每周频率:\n",
      "DatetimeIndex(['2023-01-01', '2023-01-08', '2023-01-15', '2023-01-22',\n",
      "               '2023-01-29'],\n",
      "              dtype='datetime64[ns]', freq='W-SUN')\n"
     ]
    }
   ],
   "source": [
    "# 基本用法\n",
    "dates = pd.date_range(start='2023-01-01', end='2023-01-10')\n",
    "print(\"基本日期范围:\")\n",
    "print(dates)\n",
    "\n",
    "# 指定周期数\n",
    "dates_periods = pd.date_range(start='2023-01-01', periods=10)\n",
    "print(\"\\n指定周期数:\")\n",
    "print(dates_periods)\n",
    "\n",
    "# 指定频率\n",
    "dates_freq = pd.date_range(start='2023-01-01', periods=5, freq='W')\n",
    "print(\"\\n每周频率:\")\n",
    "print(dates_freq)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.2 自定义频率\n",
    "\n",
    "通过在频率代码前添加数字，可以创建自定义间隔的日期序列：\n",
    "\n",
    "**语法格式**：`数字 + 频率代码`\n",
    "\n",
    "**常见应用场景**：\n",
    "\n",
    "| 自定义频率 | 说明 | 应用场景 |\n",
    "|-----------|------|---------|\n",
    "| `2D` | 每2天 | 隔日报表 |\n",
    "| `3W` | 每3周 | 季度性检查 |\n",
    "| `2M` | 每2个月 | 双月报告 |\n",
    "| `4H` | 每4小时 | 监控数据采集 |\n",
    "| `30T` | 每30分钟 | 高频交易数据 |\n",
    "| `15S` | 每15秒 | 实时监控 |\n",
    "| `2B` | 每2个工作日 | 工作日报表 |\n",
    "\n",
    "**注意事项**：\n",
    "- 数字必须是正整数\n",
    "- 某些频率组合可能产生意外结果（如`2M`不是精确的60天）\n",
    "- 月末、季度末等频率会自动调整到正确的结束日期"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "不同频率示例:\n",
      "D  (天   ): 2023-01-01 00:00:00 -> 2023-01-02 00:00:00 -> 2023-01-03 00:00:00\n",
      "W  (周   ): 2023-01-01 00:00:00 -> 2023-01-08 00:00:00 -> 2023-01-15 00:00:00\n",
      "M  (月末  ): 2023-01-31 00:00:00 -> 2023-02-28 00:00:00 -> 2023-03-31 00:00:00\n",
      "MS (月初  ): 2023-01-01 00:00:00 -> 2023-02-01 00:00:00 -> 2023-03-01 00:00:00\n",
      "Q  (季度末 ): 2023-03-31 00:00:00 -> 2023-06-30 00:00:00 -> 2023-09-30 00:00:00\n",
      "QS (季度初 ): 2023-01-01 00:00:00 -> 2023-04-01 00:00:00 -> 2023-07-01 00:00:00\n",
      "Y  (年末  ): 2023-12-31 00:00:00 -> 2024-12-31 00:00:00 -> 2025-12-31 00:00:00\n",
      "YS (年初  ): 2023-01-01 00:00:00 -> 2024-01-01 00:00:00 -> 2025-01-01 00:00:00\n",
      "H  (小时  ): 2023-01-01 00:00:00 -> 2023-01-01 01:00:00 -> 2023-01-01 02:00:00\n",
      "T  (分钟  ): 2023-01-01 00:00:00 -> 2023-01-01 00:01:00 -> 2023-01-01 00:02:00\n",
      "S  (秒   ): 2023-01-01 00:00:00 -> 2023-01-01 00:00:01 -> 2023-01-01 00:00:02\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/var/folders/9b/jb3nnnqn60x3dtlll6mcf0000000gp/T/ipykernel_47080/2406984279.py:19: FutureWarning: 'M' is deprecated and will be removed in a future version, please use 'ME' instead.\n",
      "  dates = pd.date_range('2023-01-01', periods=3, freq=freq)\n",
      "/var/folders/9b/jb3nnnqn60x3dtlll6mcf0000000gp/T/ipykernel_47080/2406984279.py:19: FutureWarning: 'Q' is deprecated and will be removed in a future version, please use 'QE' instead.\n",
      "  dates = pd.date_range('2023-01-01', periods=3, freq=freq)\n",
      "/var/folders/9b/jb3nnnqn60x3dtlll6mcf0000000gp/T/ipykernel_47080/2406984279.py:19: FutureWarning: 'Y' is deprecated and will be removed in a future version, please use 'YE' instead.\n",
      "  dates = pd.date_range('2023-01-01', periods=3, freq=freq)\n",
      "/var/folders/9b/jb3nnnqn60x3dtlll6mcf0000000gp/T/ipykernel_47080/2406984279.py:19: FutureWarning: 'H' is deprecated and will be removed in a future version, please use 'h' instead.\n",
      "  dates = pd.date_range('2023-01-01', periods=3, freq=freq)\n",
      "/var/folders/9b/jb3nnnqn60x3dtlll6mcf0000000gp/T/ipykernel_47080/2406984279.py:19: FutureWarning: 'T' is deprecated and will be removed in a future version, please use 'min' instead.\n",
      "  dates = pd.date_range('2023-01-01', periods=3, freq=freq)\n",
      "/var/folders/9b/jb3nnnqn60x3dtlll6mcf0000000gp/T/ipykernel_47080/2406984279.py:19: FutureWarning: 'S' is deprecated and will be removed in a future version, please use 's' instead.\n",
      "  dates = pd.date_range('2023-01-01', periods=3, freq=freq)\n"
     ]
    }
   ],
   "source": [
    "# 常用频率代码\n",
    "frequencies = {\n",
    "    'D': '天',\n",
    "    'W': '周',\n",
    "    'M': '月末',\n",
    "    'MS': '月初',\n",
    "    'Q': '季度末',\n",
    "    'QS': '季度初',\n",
    "    'Y': '年末',\n",
    "    'YS': '年初',\n",
    "    'H': '小时',\n",
    "    'T': '分钟',\n",
    "    'S': '秒'\n",
    "}\n",
    "\n",
    "print(\"不同频率示例:\")\n",
    "for freq, desc in frequencies.items():\n",
    "    try:\n",
    "        dates = pd.date_range('2023-01-01', periods=3, freq=freq)\n",
    "        print(f\"{freq:2} ({desc:4}): {dates[0]} -> {dates[1]} -> {dates[2]}\")\n",
    "    except:\n",
    "        print(f\"{freq:2} ({desc:4}): 生成失败\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "## 3. 其他日期创建方法\n",
    "\n",
    "除了`to_datetime()`和`date_range()`，Pandas还提供了其他专门的日期创建函数：\n",
    "\n",
    "### 3.1 pd.period_range() - 周期范围\n",
    "\n",
    "**用途**：创建固定周期的时间序列（如月度、季度数据）\n",
    "\n",
    "**特点**：\n",
    "- 返回`PeriodIndex`对象，而不是`DatetimeIndex`\n",
    "- 表示时间段而非时间点\n",
    "- 适合财务报表、统计报告等场景\n",
    "\n",
    "**与DatetimeIndex的区别**：\n",
    "- `DatetimeIndex`：表示精确的时间点（如2023-01-15 14:30:00）\n",
    "- `PeriodIndex`：表示时间段（如2023-01整个月）\n",
    "\n",
    "### 3.2 pd.timedelta_range() - 时间差范围\n",
    "\n",
    "**用途**：创建时间差序列\n",
    "\n",
    "**应用场景**：\n",
    "- 计算相对时间（如\"订单后3天\"）\n",
    "- 创建时间偏移量\n",
    "- 时间窗口分析\n",
    "\n",
    "### 3.3 从DataFrame组件创建\n",
    "\n",
    "**用途**：当日期数据分散在多个列中时（年、月、日分别存储）\n",
    "\n",
    "**优势**：\n",
    "- 直接从现有数据结构创建\n",
    "- 无需手动拼接字符串\n",
    "- 自动处理日期有效性\n",
    "\n",
    "**要求**：DataFrame必须包含`year`、`month`、`day`列（可选`hour`、`minute`、`second`）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "自定义频率:\n",
      "2D  (每2天     ): 2023-01-01 00:00:00 -> 2023-01-03 00:00:00\n",
      "3W  (每3周     ): 2023-01-01 00:00:00 -> 2023-01-22 00:00:00\n",
      "2M  (每2个月    ): 2023-01-31 00:00:00 -> 2023-03-31 00:00:00\n",
      "4H  (每4小时    ): 2023-01-01 00:00:00 -> 2023-01-01 04:00:00\n",
      "30T (每30分钟   ): 2023-01-01 00:00:00 -> 2023-01-01 00:30:00\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/var/folders/9b/jb3nnnqn60x3dtlll6mcf0000000gp/T/ipykernel_47080/2391160400.py:12: FutureWarning: 'M' is deprecated and will be removed in a future version, please use 'ME' instead.\n",
      "  dates = pd.date_range('2023-01-01', periods=3, freq=freq)\n",
      "/var/folders/9b/jb3nnnqn60x3dtlll6mcf0000000gp/T/ipykernel_47080/2391160400.py:12: FutureWarning: 'H' is deprecated and will be removed in a future version, please use 'h' instead.\n",
      "  dates = pd.date_range('2023-01-01', periods=3, freq=freq)\n",
      "/var/folders/9b/jb3nnnqn60x3dtlll6mcf0000000gp/T/ipykernel_47080/2391160400.py:12: FutureWarning: 'T' is deprecated and will be removed in a future version, please use 'min' instead.\n",
      "  dates = pd.date_range('2023-01-01', periods=3, freq=freq)\n"
     ]
    }
   ],
   "source": [
    "# 自定义频率\n",
    "custom_freqs = [\n",
    "    ('2D', '每2天'),\n",
    "    ('3W', '每3周'),\n",
    "    ('2M', '每2个月'),\n",
    "    ('4H', '每4小时'),\n",
    "    ('30T', '每30分钟')\n",
    "]\n",
    "\n",
    "print(\"自定义频率:\")\n",
    "for freq, desc in custom_freqs:\n",
    "    dates = pd.date_range('2023-01-01', periods=3, freq=freq)\n",
    "    print(f\"{freq:3} ({desc:8}): {dates[0]} -> {dates[1]}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "\n",
    "## 4. 实际应用示例\n",
    "\n",
    "### 4.1 金融场景：股票交易日\n",
    "\n",
    "在金融数据分析中，经常需要生成交易日序列：\n",
    "\n",
    "**工作日频率（'B'）的特点**：\n",
    "- 自动排除周六和周日\n",
    "- 不考虑节假日（需要额外处理）\n",
    "- 适用于大多数股票市场\n",
    "\n",
    "**实际应用**：\n",
    "- 计算交易日数量\n",
    "- 生成股票价格的时间索引\n",
    "- 对齐不同市场的交易数据\n",
    "\n",
    "**注意事项**：\n",
    "- 不同国家的交易日可能不同\n",
    "- 需要考虑法定节假日\n",
    "- 可以使用`pd.bdate_range()`并配合`holidays`参数处理节假日\n",
    "\n",
    "### 4.2 财务场景：月末报表日期\n",
    "\n",
    "财务报表通常在月末、季度末、年末生成：\n",
    "\n",
    "**月末频率（'M'）的特点**：\n",
    "- 自动定位到每月最后一天\n",
    "- 正确处理大小月（28/29/30/31天）\n",
    "- 自动处理闰年2月\n",
    "\n",
    "**应用场景**：\n",
    "- 生成财务报表日期\n",
    "- 创建账单周期\n",
    "- 计算月度KPI\n",
    "\n",
    "**相关频率**：\n",
    "- `MS`：月初（Month Start）\n",
    "- `Q`：季度末\n",
    "- `Y`：年末\n",
    "- `BM`：工作日月末（避开周末）\n",
    "\n",
    "---\n",
    "\n",
    "## 总结\n",
    "\n",
    "本教程介绍了Pandas中日期时间创建和转换的核心方法：\n",
    "\n",
    "### 关键要点\n",
    "\n",
    "1. **`pd.to_datetime()`**：万能的日期转换函数\n",
    "   - 自动识别多种格式\n",
    "   - 使用`format`参数提升性能\n",
    "   - 用`errors`参数处理无效数据\n",
    "\n",
    "2. **`pd.date_range()`**：创建规则日期序列\n",
    "   - 灵活的参数组合\n",
    "   - 丰富的频率代码\n",
    "   - 支持自定义间隔\n",
    "\n",
    "3. **其他方法**：针对特定场景\n",
    "   - `period_range()`：周期数据\n",
    "   - `timedelta_range()`：时间差\n",
    "   - DataFrame组件：分散的日期数据\n",
    "\n",
    "### 最佳实践\n",
    "\n",
    "✅ **DO（推荐做法）**：\n",
    "- 处理大量数据时指定`format`参数\n",
    "- 使用`errors='coerce'`处理脏数据\n",
    "- 根据业务需求选择合适的频率代码\n",
    "- 使用工作日频率处理金融数据\n",
    "\n",
    "❌ **DON'T（避免做法）**：\n",
    "- 不要在循环中反复调用`to_datetime()`\n",
    "- 不要忽略时区信息（国际化应用）\n",
    "- 不要假设所有月份都是30天\n",
    "- 不要混淆`DatetimeIndex`和`PeriodIndex`\n",
    "\n",
    "### 下一步学习\n",
    "\n",
    "- **02-日期时间索引和时间序列**：学习如何使用日期作为索引\n",
    "- **03-日期时间运算和比较**：掌握日期的加减和比较操作\n",
    "- **04-时间序列重采样**：学习频率转换和数据聚合"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "ml311",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
